import router from './router'
import { getToken } from './utils/auth'
const whiteList = ['/login', '/codeControl']
import useUserStore from '@/store/modules/userStore'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'
import useDictStore from '@/store/modules/dict'

router.beforeEach((to, from, next) => {
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    if (to.path == 'login') {
      next({ path: '/' })
    } else {
      const userStore = useUserStore()
      const dictStore = useDictStore()
      if (!userStore.name) {
        userStore
          .init()
          .then(() => {
            next()
          })
          .catch((err) => {
            userStore.logOut().then(() => {
              ElMessage.error(err)
              next({ path: '/' })
            })
          })
        dictStore.initDict()
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) != -1) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})
